package com.kgd.news.wxpay.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jfinal.template.ext.directive.Date;
import com.kgd.news.entity.Order;
import com.kgd.news.entity.SysUser;
import com.kgd.news.entity.UserCashRecord;
import com.kgd.news.utils.DateUtils;
import com.kgd.news.utils.StringUtilsWx;
import com.kgd.news.utils.wx.WxHelper;
import com.kgd.news.wxpay.constant.Constant;
import com.kgd.news.wxpay.controller.TransferController;
import com.kgd.news.wxpay.entity.PayInfo;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderUtils {
    private static final Logger log = Logger.getLogger(OrderUtils.class);

    /**
     * 查询微信后台订单支付状态
     *
     * @param order
     */
    public static Map<String, String> wxOrderquery(Order order) {
        Map<String, String> result = new HashMap();
        Map map = new HashMap();
        String openId = order.getUserid();
        String info = "";
        log.error("openid: " + openId);
        try {
            if (StringUtilsWx.isEmpty(openId)) {
                info = "获取到openId为空";
            } else {
                openId = openId.replace("\"", "").trim();
                Long timeStamp = System.currentTimeMillis() / 1000;
                String nonce_str = RandomUtils.generateMixString(32);
                String transaction_id = order.getWxTransactionId();
                String out_trade_no = order.getOrderid();
                String stringSignTemp = "appid=" + WxHelper.getAppId() + "&mch_id=" + Constant.MCH_ID + "&nonce_str=" + nonce_str + "&out_trade_no=" + out_trade_no +
                        "&sign_type=MD5" + "&transaction_id=" + transaction_id;
//              再次签名，这个签名用于小程序端调用wx.requesetPayment方法
//              WxPayConfig.key
//              这里必须注意，签名里有多少参数，xml里面也要有多少参数的，比如sign_type默认为MD5的话，可以省略的
                String querySign = PayUtils.sign(stringSignTemp, Constant.APP_KEY, "utf-8").toUpperCase();
                map.put("appid", WxHelper.getAppId());
                map.put("mch_id", Constant.MCH_ID);
                map.put("sign_type", "MD5");
                map.put("nonce_str", nonce_str);
                map.put("transaction_id", transaction_id);
                map.put("out_trade_no", out_trade_no);
                map.put("sign", querySign);
                StringBuffer buffer = HttpUtil.httpsRequest(Constant.URL_ORDER_QUERY, "POST", XmlUtil.xmlFormat(map, false));
                log.error("queryOrder request return body: \n" + buffer.toString());
                result = CommonUtil.parseXml(buffer.toString());
                String return_code = result.get("return_code");
                if (!StringUtilsWx.isEmpty(return_code) && return_code.equals("SUCCESS")) {
                    log.error("return_code:" + return_code);
                }
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param order
     * @param cash_amounts_int 检查订单金额
     */
    public static boolean checkOrderAndCash(Order order, int cash_amounts_int) {
        Map<String, String> restmap = wxOrderquery(order);
        String return_code = restmap.get("return_code");
        if (!StringUtilsWx.isEmpty(return_code) && return_code.equals("SUCCESS")) {
            if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("result_code"))) {
                log.info("查询转账成功：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
                String total_fee = restmap.get("total_fee");
                int total_fee_int = -1;
                try {
                    total_fee_int = Integer.parseInt(total_fee);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
//                    支付成功并且订单金额相同
                order.setState(Constant.ORDER_STATE_SUCCESS);
                String openid = order.getUserid();
                String orderid = order.getOrderid();
                int ordercount = order.getOrdercount();
                int orderfee = order.getOrderfee();
                int costfee = order.getCostFee();
                if (cash_amounts_int != orderfee) {
                    return false;
                }
                int acountDeduct = order.getAcountdeduct();
                if (total_fee_int == (orderfee - acountDeduct)) {
                    PayUtils.splitMoney(orderfee, ordercount, openid, orderid,costfee);
                    RedPacketSplitUtil.addCashToUser(orderid, openid, acountDeduct, "检查订单金额时，从账户扣钱数",Constant.USER_CASHTYPE_EXPEND);
//                    List<SysUser> sysUsers = SysUser.dao.find("select * from sys_user where userid = ?", openid);
//                    if (sysUsers != null && sysUsers.size() == 1) {
//                        SysUser sysUser = sysUsers.get(0);
//
//                        int balance = sysUser.getBalance() == null ? 0 : sysUser.getBalance();
//                        sysUser.setBalance(balance - acountDeduct);
//                        sysUser.update();
//                        recordUserCash(-acountDeduct, orderid, openid, balance - acountDeduct, "订单状态未成功，重新查询后台后修改sysUser",Constant.USER_CASHTYPE_EXPEND);
//                    } else {
////用户不存在
//                        return false;
//                    }
                    order.update();
                    return true;
//                    去修改order表，去分钱到Split_hb,
                } else {
//                    订单金额不对的
                    return false;
                }

            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * @param fee
     * @param orderid
     * @param userid
     * @param balance
     * @param attach
     * @param cashtype
     * 记录用户账户明细表
     */
    public static boolean  recordUserCash(int fee,String orderid,String userid,int balance,String attach,int cashtype) {
        UserCashRecord userCashRecord = new UserCashRecord();
        userCashRecord.setCreatetime(DateUtils.getCurTimessSS());
        userCashRecord.setFee(fee);
        userCashRecord.setCashtype(cashtype);
        userCashRecord.setOrderid(orderid);
        userCashRecord.setUserid(userid);
        userCashRecord.setBalance(balance);
        userCashRecord.setAttach(attach);
        return userCashRecord.save();
    }
}
